<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\User;
use app\common\tool\Result;
use think\exception\ValidateException;
use app\common\model\Signup;
use app\common\model\Cate;

class Login extends Base
{

    /**
     * 登录
     */
    public function check()
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'Login');
            $user = User::where('id_card', $param['id_card'])->find();
            if (empty($user)) return Result::fail('账号不存在');

            if ($user['password'] != md5($param['password'])) {
                return Result::fail('密码错误');
            }
            if ($user['is_lock'] == 1) {
                return Result::fail('账号已冻结');
            }
            $time = time();
            $token = md5(json_encode($user) . $time . $this->request->ip());
            $user->token = $token;
            $user->last_time = $time;
            $user->last_ip = $this->request->ip();
            $user->save();
            return Result::fastReturn(['code' => 1, 'msg' => '登录成功', 'token' => $token]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        } catch (ValidateException $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 报名
     */
    public function signup()
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'Signup');
            return Result::fastReturn(Signup::add($param));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        } catch (ValidateException $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取课程等级
    */
    public function getCate()
    {
        try {
            $list =Cate::where('pid',0)->field('id,title')->select();
            return Result::success('获取成功！', $list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取图片
     */
    public function getImages()
    {
        $sys = \app\common\controller\Config::lists();
        try {
            $param = $this->request->get();
            $img = $sys[$param['type']]??'';
            return Result::success('获取成功！', $img);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取网站信息
     */
    public function getWeb()
    {
        $sys = \app\common\controller\Config::lists();
        try {
            $web = [
                'web_site_title'=>$sys['web_site_title'],
                'web_site_logo'=>$sys['web_site_logo'],
            ];
            return Result::success('获取成功！', $web);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
